<template>
  <Form :disabled="type === 'view'" @failed="onFailed" @submit="onSubmit">
    <CellGroup>
      <Field
        v-if="['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isTitle)"
        v-model="formData.voteEnrollName"
        :required="voteInfo.appBizVoteEnrollConfig.isTitle === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isTitle === 'Y',
            message: '请填写名称',
          },
        ]"
        label="名称"
        maxlength="20"
        name="名称"
        placeholder="请填写名称"
      />
      <Field
        v-if="['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isAuthor)"
        v-model="formData.authorName"
        :required="voteInfo.appBizVoteEnrollConfig.isAuthor === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isAuthor === 'Y',
            message: '请填写作者',
          },
        ]"
        label="作者"
        maxlength="8"
        name="作者"
        placeholder="请填写作者"
      />
      <Field
        v-if="['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isTraidunion)"
        v-model="formData.orgName"
        :required="voteInfo.appBizVoteEnrollConfig.isTraidunion === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isTraidunion === 'Y',
            message: '请填写所属工会',
          },
        ]"
        is-link
        label="所属工会"
        name="所属工会"
        placeholder="请填写所属工会"
        readonly
        @click="handleOrg('orgs')"
      />
      <Field
        v-if="['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isFirm)"
        v-model="formData.candidateFirm"
        :required="voteInfo.appBizVoteEnrollConfig.isFirm === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isFirm === 'Y',
            message: '请填写单位名称',
          },
        ]"
        label="单位名称"
        maxlength="32"
        name="单位名称"
        placeholder="请填写单位名称"
      />
      <Field
        v-if="
          ['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isGroup) &&
          voteInfo.appBizVoteGroup.length
        "
        v-model="formData.voteGroupName"
        :required="voteInfo.appBizVoteEnrollConfig.isGroup === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isGroup === 'Y',
            message: '请填写分组',
          },
        ]"
        is-link
        label="分组"
        name="分组"
        placeholder="请填写分组"
        readonly
        @click="handleOrg('groups')"
      />
      <Field
        v-if="['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isAttachment)"
        :required="voteInfo.appBizVoteEnrollConfig.isAttachment === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isAttachment === 'Y',
            message: '请填写图片',
          },
        ]"
        label="图片"
        label-align="top"
        name="图片"
        placeholder="请填写图片"
      >
        <template #input>
          <Uploader
            v-model="files"
            :deletable="type !== 'view'"
            :disabled="type === 'view'"
            :max-count="5"
            :max-size="
              (voteInfo.appBizVoteEnrollConfig.imageSize || Infinity) *
              1024 *
              1024
            "
            multiple
            @oversize="oversize"
          />
        </template>
      </Field>
      <Field
        v-if="
          ['Y', 'N'].includes(voteInfo.appBizVoteEnrollConfig.isDescription)
        "
        v-model="formData.voteEnrollDesc"
        :required="voteInfo.appBizVoteEnrollConfig.isDescription === 'Y'"
        :rules="[
          {
            required: voteInfo.appBizVoteEnrollConfig.isDescription === 'Y',
            message: '请填写简介',
          },
        ]"
        autosize
        label="简介"
        label-align="top"
        name="简介"
        placeholder="请填写简介"
        rows="4"
        type="textarea"
      />
    </CellGroup>
    <div v-if="type !== 'view'" style="margin: 16px">
      <Button
        :disabled="loading"
        :loading="loading"
        block
        native-type="submit"
        round
        type="primary"
        >提交</Button
      >
    </div>
  </Form>
  <Popup v-model:show="showPicker" position="bottom">
    <Picker
      :columns="columns"
      @cancel="showPicker = false"
      @confirm="onConfirm"
    />
  </Popup>
</template>
<script setup>
import {
  addVote,
  getEnrollInfo,
  getSzOrgInfo,
} from "@/server/business/vote.js";
import { uploadFile } from "@/server/common/file.js";
import { formatDate } from "@/utils/common.js";
import {
  Button,
  CellGroup,
  closeToast,
  Field,
  Form,
  Picker,
  Popup,
  showLoadingToast,
  showNotify,
  Uploader,
} from "vant";
import { store } from "./components/store.js";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const voteInfo = ref(store.voteInfo);
const userInfo = ref(store.userInfo);
const files = ref([]);
const showPicker = ref(false);
const columns = ref([]);
const loading = ref(false);
const type = ref("add");
const formData = reactive({
  authorName: userInfo.value.name,
  enrollDate: formatDate(new Date(), "yyyy-MM-dd hh:mm:ss"),
  orgId: "",
  orgName: "",
  sloganUrls: [],
  voteEnrollDesc: "",
  voteEnrollName: "",
  voteGroupId: "",
  voteGroupName: "",
  voteId: route.query.id,
  candidateFirm: userInfo.value.companyName,
  userInfo: userInfo.value,
});
const colList = reactive({
  orgs: [],
  groups: (voteInfo.value.appBizVoteGroup || []).map((item) => {
    return { text: item.groupName, value: item.voteGroupId };
  }),
  type: "",
  handleorgs: (obj) => {
    // 选择工会
    formData.orgName = obj.text;
    formData.orgId = obj.value;
  },
  handlegroups: (obj) => {
    // 选择分组
    formData.voteGroupId = obj.value;
    formData.voteGroupName = obj.text;
  },
});
// 确认选择
const onConfirm = ({ selectedOptions }) => {
  if (selectedOptions[0]) {
    colList["handle" + colList.type](selectedOptions[0]);
  }
  showPicker.value = false;
};
// 打开选择器
const handleOrg = (name) => {
  if (type.value === "view") return; // 查看进来 不可以点击
  columns.value = colList[name] || [];
  colList.type = name;
  showPicker.value = true;
};
// 获取工会列表
const getUntion = () => {
  getSzOrgInfo().then((res) => {
    colList.orgs = (res.data || []).map((item) => {
      return { text: item.orgName, value: item.orgCode };
    });
  });
};
// 提交 新增或修改
const onSubmit = async () => {
  showLoadingToast({ message: "提交中...", forbidClick: true, duration: 0 });
  loading.value = true;
  if (files.value.length) {
    formData.sloganUrls = await uploadFileFunc(files.value);
  }
  let params = JSON.parse(JSON.stringify(formData));
  delete params.voteGroupName;
  addVote({ save_request: params })
    .then(() => {
      loading.value = false;
      showNotify({ type: "success", message: "报名成功" });
      closeToast();
      router.back();
    })
    .catch(() => {
      loading.value = false;
      closeToast();
    });
};
// 提交表单报错 调试用
const onFailed = (errorInfo) => {
  console.log("failed", errorInfo);
};
// 文件上传
const uploadFileFunc = (item) => {
  return new Promise((resolve) => {
    let pall = item.map((file) => {
      if (file.file || file.raw) {
        let formDate = new FormData();
        formDate.append("file", file.file || file.raw);
        return uploadFile(formDate);
      } else {
        return Promise.resolve({ data: file });
      }
    });
    Promise.all(pall)
      .then((res) => {
        let list = res.map((next) => next.data.url);
        resolve(list);
      })
      .catch((msg) => console.error(msg));
  });
};
// 获取报名内容详情
const getEnroll = () => {
  getEnrollInfo({
    get_request: { voteEnrollId: route.query.voteEnrollId },
  }).then((res) => {
    for (let key in formData) {
      formData[key] = res.data[key];
    }
    formData.voteGroupName = colList.groups.filter(
      (item) => item.value === formData.voteGroupId,
    )[0]?.text;
    formData.sloganUrls = formData.sloganUrls.length
      ? formData.sloganUrls
      : (formData.sloganUrl || "").split("split");
    files.value = formData.sloganUrls.map((img) => {
      return { url: img };
    });
    formData.voteEnrollId = route.query.voteEnrollId;
  });
};
// 文件超出大小限制时
const oversize = () => {
  showNotify({
    type: "danger",
    message: `图片不可以超过${voteInfo.value.appBizVoteEnrollConfig.imageSize}M`,
  });
};
// 初始化集合
const getApis = {
  add: () => {},
  update: () => getEnroll(),
  view: () => getEnroll(),
};
// 初始化
const init = () => {
  if (route.query.type) {
    type.value = route.query.type;
    getApis[type.value]();
  }
  getUntion();
};
init();
</script>
